from datetime import datetime
import os
import platform
import sys

class SystemUtil:

    @staticmethod
    def is_admin():
        """
        判断当前进程是否有管理员/root权限
        """
        if platform.system() == 'Windows':
            import ctypes
            try:
                return ctypes.windll.shell32.IsUserAnAdmin()
            except Exception:
                return False
        else:
            return os.geteuid() == 0
        
    @staticmethod
    def run_as_admin():
        """
        Windows下自动提升为管理员权限
        Linux下自动尝试使用sudo重新运行
        """
        if platform.system() == 'Windows':
            import ctypes
            if not SystemUtil.is_admin():
                print("正在尝试以管理员权限重新运行...")
                ctypes.windll.shell32.ShellExecuteW(
                    None, "runas", sys.executable, " ".join(sys.argv), None, 1)
                sys.exit(0)
        else:
            if not SystemUtil.is_admin():
                print("正在尝试以管理员权限重新运行...")
                try:
                    os.execvp("sudo", ["sudo", sys.executable] + sys.argv)
                except Exception as e:
                    print(f"提权失败: {e}")
                    print("请手动使用 sudo 运行本脚本。")
                    sys.exit(1)


    @staticmethod
    def get_current_timestamp_ms():
        """
        获取当前时间戳，单位毫秒
        """
        return int(datetime.now().timestamp() * 1000)
    
    @staticmethod
    def set_system_time(timestamp_ms : int = get_current_timestamp_ms()):
        datetime_str = datetime.fromtimestamp(timestamp_ms / 1000).strftime('%Y-%m-%d %H:%M:%S')
        import subprocess
        if platform.system() == 'Windows':
            try:
                date_part, time_part = datetime_str.split(' ')
                date_cmd = f'date {date_part}'
                time_cmd = f'time {time_part}'
                subprocess.check_call(date_cmd, shell=True)
                print(f"执行命令: {date_cmd}")
                subprocess.check_call(time_cmd, shell=True)
                print(f"执行命令: {time_cmd}")
                return True, "设置成功"
            except Exception as e:
                return False, f"出现了未知错误: {e}"
        elif platform.system() == 'Linux':
            try:
                cmd = f'timedatectl set-time "{datetime_str}"'
                subprocess.check_call(cmd, shell=True)
                print(f"执行命令: {cmd}")
                # subprocess.check_call('hwclock --systohc', shell=True)
                return True, "设置成功"
            except Exception as e:
                return False, f"出现了未知错误: {e}"
        else:
            return False, "不支持的系统平台"
        
    @staticmethod
    def sntp_sync_time(url : str):
        """
        同步系统时间（支持 Linux 和 Windows）
        :param url: NTP 服务器地址
        :return: (bool, str) 同步结果和消息
        """
        import subprocess
        import platform
        
        if not url or not isinstance(url, str):
            return False, "无效的 NTP 服务器地址"
        
        try:
            if platform.system() == 'Linux':
                cmd = f'sntp -S {url}'
                subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
                print(f"执行命令: {cmd}")
                return True, "时间同步成功"
            elif platform.system() == 'Windows':
                # cmd = f'w32tm /config /syncfromflags:manual /manualpeerlist:{url}'
                # subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
                # subprocess.run('w32tm /resync /force', shell=True, check=True, capture_output=True, text=True)
                # return True, "时间同步成功"
                return False, "不支持的系统平台"
            else:
                return False, "不支持的系统平台"
        except subprocess.CalledProcessError as e:
            return False, f"时间同步失败: {e}"
        except Exception as e:
            return False, f"未知错误: {e}"

    @staticmethod
    def timestamp_to_string(timestamp_ms : int = get_current_timestamp_ms()):
        """
        时间戳转字符串
        """
        return datetime.fromtimestamp(timestamp_ms / 1000).strftime('%Y-%m-%d %H:%M:%S')

    @staticmethod
    def timestamp_to_string_ms(timestamp_ms : int = get_current_timestamp_ms()):
        """
        时间戳转字符串，精确到毫秒
        """
        return datetime.fromtimestamp(timestamp_ms / 1000).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

    @staticmethod
    def timestamp_to_string_for_path(timestamp_ms : int = get_current_timestamp_ms()):
        """
        时间戳转字符串，用于文件路径
        """
        return datetime.fromtimestamp(timestamp_ms / 1000).strftime('%Y%m%d_%H%M%S')

    @staticmethod
    def timestamp_to_string_ms_for_path(timestamp_ms : int = get_current_timestamp_ms()):
        """
        时间戳转字符串，用于文件路径，精确到毫秒
        """
        return datetime.fromtimestamp(timestamp_ms / 1000).strftime('%Y%m%d_%H%M%S%f')[:-3]

    @staticmethod
    def generate_date_string(timestamp_ms : int = get_current_timestamp_ms()):
        """
        生成日期字符串
        """
        return datetime.fromtimestamp().strftime('%Y%m%d')

    if __name__ == '__main__':
        print(get_current_timestamp_ms())

        print(timestamp_to_string())
        print(timestamp_to_string_ms())

        print(sntp_sync_time("ntp.aliyun.com"))
